package com.wx.forum.controller;

import com.wx.forum.common.AppResult;
import com.wx.forum.common.ResultCode;
import com.wx.forum.contant.Contants;
import com.wx.forum.model.Article;
import com.wx.forum.model.Board;
import com.wx.forum.model.User;
import com.wx.forum.service.IArticleService;
import com.wx.forum.service.IAuthService;
import com.wx.forum.service.IBoardService;
import com.wx.forum.service.IUserService;
import com.wx.forum.utils.JwtUtil;
import com.wx.forum.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "文章接口")
@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Resource
    private IArticleService articleService;
    @Resource
    private IUserService userService;
    @Resource
    private IBoardService boardService;
    @Autowired
    private IAuthService authService;


    @ApiOperation("发布帖子")
    @RequestMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @ApiParam("板块id") @RequestParam("boardId") @NonNull Long boardId,
                            @ApiParam("文章名") @RequestParam("title") @NonNull String title,
                            @ApiParam("文章内容") @RequestParam("content") @NonNull String content) {
        //1.校验用户是否被禁言
        //通过token获取用户信息
        String token = request.getHeader(Contants.USER_TOKEN_HANDER);
        Long userId = JwtUtil.getIdByToken(token);
        User user = userService.selectById(userId);
        //校验
        if (user.getState() == 1) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //2.校验板块信息
        Board board = boardService.selectById(boardId);
        if (board.getDeleteState() == 1 || board.getState() == 1) {
            log.warn(ResultCode.FAILED_NOT_EXISTS.toString());
            return AppResult.failed(ResultCode.FAILED_NOT_EXISTS);
        }
        //3.构造文章对象
        Article article = new Article();
        article.setTitle(title);
        article.setContent(content);
        article.setUserId(userId);
        article.setBoardId(boardId);
        //4.添加帖子
        articleService.creat(article);
        return AppResult.success();
    }

    @ApiOperation("查询所有帖子列表")
    @GetMapping("getAllArticleList")
    public AppResult<List<Article>> getAllArticleList(
            @ApiParam("板块id") @RequestParam(value = "boardId", required = false) Long boardId) {
        List<Article> articleList = null;

        //boardId为空时，查询所有
        if (boardId == null) {
            articleList = articleService.selectAll();
            //boardId不为空时，根据id查询帖子列表
        } else {
            articleList = articleService.selectAllByBoardId(boardId);
        }

        if (articleList == null) {
            //如果结果为空，则创建一个空集合
            articleList = new ArrayList<>();
        }

        //返回结果
        return AppResult.success(articleList);
    }

    /**
     * 根据帖子id查找帖子详情
     * @param id 帖子id
     * @return
     */
    @ApiOperation("查询帖子详情")
    @GetMapping("/getDetails")
    public AppResult<Article> getDetails(HttpServletRequest request,
            @ApiParam("帖子id") @RequestParam("id") @NonNull Long id){
        //1.查询帖子详情
        Article article = articleService.selectDetailById(id);
        if(article == null){
            log.warn(ResultCode.FAILED_NOT_EXISTS.toString());
            return AppResult.failed(ResultCode.FAILED_NOT_EXISTS);
        }
        //2.判断是否是作者本人
        //通过token获取id
        String token = request.getHeader(Contants.USER_TOKEN_HANDER);
        Long userId = JwtUtil.getIdByToken(token);
        if (userId == null || StringUtil.isEmpty(token)) {
            //用户未登录
            //打印信息
            log.warn(ResultCode.FAILED_FORBIDDEN.toString());
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //判断
        if(article.getUserId() == userId){
            //是作者
            article.setOwn(true);
        }
        //返回数据
        return AppResult.success(article);

    }

    /**
     * 更新帖子
     * @param id
     * @param content
     * @param title
     * @return
     */
    @ApiOperation("更新帖子")
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request,
            @ApiParam("帖子id") @RequestParam("id") @NonNull Long id,
            @ApiParam("帖子内容") @RequestParam("content") @NonNull String content,
            @ApiParam("帖子标题") @RequestParam("title") @NonNull String title){
        //1.判断用户是否处于禁言状态
        //通过token获取id
        String token = request.getHeader(Contants.USER_TOKEN_HANDER);
        Long userId = JwtUtil.getIdByToken(token);
        if (userId == null || StringUtil.isEmpty(token)) {

            //打印信息
            log.warn(ResultCode.FAILED_FORBIDDEN.toString());
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        User user = userService.selectById(userId);
        if(user.getState() == 1){
            //用户已经禁言
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //2.判断帖子信息是否合法
        //2.1查询帖子信息
        Article article = articleService.selectById(id);
        if(article == null){
            log.warn(ResultCode.FAILED_NOT_EXISTS.toString());
            return AppResult.failed(ResultCode.FAILED_NOT_EXISTS);
        }
        //2.2判断是否是作者
        if(user.getId() != article.getUserId()){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //2.3判断帖子是否被封
        if(article.getState() == 1 || article.getDeleteState() == 1){
            log.warn(ResultCode.FAILED.toString());
            return AppResult.failed(ResultCode.FAILED);
        }
        //3.更改帖子信息
        articleService.modify(id,content,title);
        log.info("更新成功  userId: " + user.getId() + "articleId: " + article.getId());
        return AppResult.success();
    }

    /**
     * 点赞帖子
     * @param id
     * @return
     */
    @ApiOperation("点赞帖子")
    @PostMapping("/thumbsUp")
    public AppResult thumbsUp(HttpServletRequest request,
            @ApiParam("帖子id") @RequestParam("id") @NonNull Long id){
        //1.判断用户是否处于禁言状态
        //通过token获取id
        String token = request.getHeader(Contants.USER_TOKEN_HANDER);
        Long userId = JwtUtil.getIdByToken(token);
        if (userId == null || StringUtil.isEmpty(token)) {

            //打印信息
            log.warn(ResultCode.FAILED_FORBIDDEN.toString());
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        User user = userService.selectById(userId);
        if(user.getState() == 1){
            //用户已经禁言
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //2.判断帖子信息是否合法
        //2.1查询帖子信息
        Article article = articleService.selectById(id);
        if(article == null){
            log.warn(ResultCode.FAILED_NOT_EXISTS.toString());
            return AppResult.failed(ResultCode.FAILED_NOT_EXISTS);
        }

        //2.2判断帖子是否封贴
        if(article.getState() == 1 || article.getDeleteState() == 1){
            log.warn(ResultCode.FAILED.toString());
            return AppResult.failed(ResultCode.FAILED);
        }
        //2.3判断是否重复点赞
        Integer newcnt;


        if(authService.repeThumbs(userId, article.getId())){
            //取消点赞
            newcnt = articleService.thumbsUpById(userId, article.getId(),-1);
        }else {
            //点赞
            newcnt =  articleService.thumbsUpById(userId,article.getId(),1);
        }
        if(newcnt == null){
           return AppResult.success("重复操作");
        }
        return AppResult.success(newcnt);
    }
    @ApiOperation("删除帖子")
    @PostMapping("/delete")
    public AppResult delete(HttpServletRequest request,
                            @ApiParam("帖子id") @RequestParam("id") @NonNull Long id){
        //1.判断用户是否处于禁言状态
        //通过token获取id
        String token = request.getHeader(Contants.USER_TOKEN_HANDER);
        Long userId = JwtUtil.getIdByToken(token);
        if (userId == null || StringUtil.isEmpty(token)) {

            //打印信息
            log.warn(ResultCode.FAILED_FORBIDDEN.toString());
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        User user = userService.selectById(userId);
        if(user.getState() == 1){
            //用户已经禁言
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //2.判断帖子信息是否合法
        //2.1查询帖子信息
        Article article = articleService.selectById(id);
        if(article == null){
            log.warn(ResultCode.FAILED_NOT_EXISTS.toString());
            return AppResult.failed(ResultCode.FAILED_NOT_EXISTS);
        }
        //2.2判断是否是作者
        if(user.getId() != article.getUserId()){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //3.删除帖子
        articleService.deleteById(id);

        return AppResult.success();
    }
    @ApiOperation("根据userId查找帖子列表")
    @GetMapping("/getByUsertId")
    public AppResult<List<Article>> getByUsertId(HttpServletRequest request,
                                                 @ApiParam("用户id") @RequestParam(value = "userId",required = false) Long userId){
        List<Article> articleList = null;
        //1.userId为空就查找当前登录用户的帖子列表
        if(userId == null){
            //通过token获取id
            String token = request.getHeader(Contants.USER_TOKEN_HANDER);
            Long id = JwtUtil.getIdByToken(token);
            if (id == null || StringUtil.isEmpty(token)) {
                //用户未登录
                //打印信息
                log.warn(ResultCode.FAILED_FORBIDDEN.toString());
                return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
            }
            articleList = articleService.selectArticleByUserId(id);

        }else {
            //2.userId有值就查找对应用户帖子列表
            articleList = articleService.selectArticleByUserId(userId);
        }

        if(articleList == null){
            articleList = new ArrayList<>();
        }

        //返回
        return AppResult.success(articleList);
    }
    @ApiOperation("搜索关键字")
    @GetMapping("/search")
    /**
     * 搜索帖子
     * @param key
     * @return
     */
    public AppResult<List<Article>> searchArticle(
            @ApiParam("搜索的关键词") @RequestParam("key") String key){
        if(StringUtil.isEmpty(key)){
            return AppResult.failed("输入结果不能为空");
        }
        //搜索关键词
        List<Article> articleList = articleService.searchArticle(key);
        return AppResult.success(articleList);
    }

}
